﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using NPMonitor.DataModel;
using NPMonitor.Implementation;
using NPMonitor.Implementation.Store;

namespace NPMonitor.Web
{
    /// <summary>
    /// Download 的摘要说明
    /// </summary>
    public class Download : IHttpHandler
    {
        int jobId = 0;

        public void ProcessRequest(HttpContext context)
        {
            string jobIdStr = context.Request["id"];
            string fileName = context.Request["filename"];

            if (String.IsNullOrEmpty(fileName))
            {
                int.TryParse(jobIdStr, out jobId);

                if (jobId != 0 && context.Response.IsClientConnected)
                {
                    JobDefinition jobDefinition = StoreManager.Current.JobDefinitionStore.GetJobDefinitionById(jobId);

                    if (jobDefinition != null)
                    {
                        fileName = jobDefinition.FileName;
                    }
                }
            }

            if (!String.IsNullOrEmpty(fileName))
            {
                string filePath = Path.Combine(FileManager.UploadFolderPath, fileName);

                ResponseFile(filePath, fileName, context);
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }

        /// <summary>
        /// 输出文件
        /// </summary>
        private void ResponseFile(string filePath, string fileName, HttpContext context)
        {
            byte[] buffer = new Byte[10000];
            int length;

            HttpResponse response = context.Response;

            context.Response.ContentType = "application/x-zip-compressed";
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlPathEncode(fileName));

            using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                long dataToRead = stream.Length;

                while (dataToRead > 0)
                {
                    if (response.IsClientConnected)
                    {
                        length = stream.Read(buffer, 0, 10000);
                        response.OutputStream.Write(buffer, 0, length);
                        response.Flush();

                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        dataToRead = -1;
                    }
                }
            }
        }
    }
}